package com.aphrodite.ui.widgets;

import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

/**
 * A list that only allows a single item to be selected
 * 
 * @author kentelt
 * 
 */
public class OptionButtonGroup extends List {
	private int currEnabled;
	// int radioHt;

	boolean[] selectedArray;

	public OptionButtonGroup(Theme theme, int width, int height) {
		super(theme, width, height);
		selectedArray = new boolean[1];
	}

	public void addItem(String item, Image icon) {
		list.addElement(item);
		icons.addElement(icon);
		updateModel();
		resizeSelArray();
		reDrawWidget();
	}

	public void fire() {
		setSelectedIndex(selIndex);
		super.fire();
	}

	/* needs to be overriden. renders the icon and the string item */
	void renderItem(final Graphics g, final boolean isSelected, final int index, final int y) {
		tmpImage = (Image) icons.elementAt(index);
		tmpString = (String) list.elementAt(index);
		/* Draw the radio button */
		// g.setColor(Theme.baseCmpColor);
		// GraphicUtil.drawCircle(g, imagePad + radioHt / 2, y + (itemHeight /
		// 2), radioHt);
		WidgetHelper.drawRadio(g, imagePad, y + (itemHeight / 2), selectedArray[index]);
		// if (selectedArray[index]) {
		// GraphicUtil.fillCircle(g, imagePad + radioHt / 2, y + (itemHeight /
		// 2), radioHt / 2);
		// }
		renderCaption(g, isSelected, y);
	}

	void renderCaption(final Graphics g, boolean isSelected, int y) {
		if (tmpImage != null) {
			// g.drawImage(tmpImage, imagePad, y + (itemHeight / 2) -
			// tmpImage.getHeight() / 2, 0);
			g.drawImage(tmpImage, imagePad + WidgetHelper.radioBtnHeight + 2, y + itemHeight / 2, Graphics.VCENTER);
		}
		if (tmpString != null) {
			g.setColor(isSelected ? theme.highLightFGColor : theme.fgColor);
			if (theme.bmFont != null) {
				theme.bmFont.drawString(g, tmpString, textStart, y + itemHeight / 2, Graphics.VCENTER);
			} else {
				g.setFont(theme.widgetFont);
				g.drawString(tmpString, textStart, y, 0);
			}
		}
	}

	private void resizeSelArray() {
		boolean[] temp = new boolean[list.size()];
		System.arraycopy(selectedArray, 0, temp, 0, selectedArray.length - 1);
		selectedArray = temp;
		// selectedArray[0] = true;
	}

	public boolean[] getSelectionList() {
		return selectedArray;
	}

	/**
	 * 
	 * @param index
	 * @throws ArrayIndexOutOfBoundsException
	 *             if an invalid <code>index</code> was specified
	 */
	public void setSelectedIndex(int index) {
		selectedArray[currEnabled] = false;
		currEnabled = index;
		selectedArray[currEnabled] = true;
		reDrawWidget();
	}

	void computeTextStart() {
		super.computeTextStart();
		// radioHt = itemHeight - 4;/* 2px pad (top & bottom) */
		// if (radioHt % 2 != 0)
		// radioHt--;
		/* icon width+ Right pad */
		textStart += WidgetHelper.radioBtnHeight;
		// System.out.println("Radio Ht " + radioHt);
	}
}
